package com.bite.common.security.service;

import cn.hutool.core.lang.UUID;
import com.bit.common.redis.service.RedisService;
import com.bite.common.core.constants.CacheConstants;
import com.bite.common.core.constants.TokenConstants;
import com.bite.common.core.domain.vo.LoginUserVO;
import com.bite.common.core.enums.UserIdentity;
import com.bite.common.core.domain.LoginUser;
import com.bite.common.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TokenService {

    @Autowired
    private RedisService redisService;

    public String createToken(Long userId, String secret, LoginUser loginUser) {
        // 本项目是可以通过ID来保证唯一性，如果保障不了 那么可以通过UUID来获取
        String key = UUID.fastUUID().toString();
        Map<String, Object> claim = new HashMap<>();
        claim.put(TokenConstants.LOGIN_USER_UUID, key);
        claim.put(TokenConstants.LOGIN_USER_ID, userId);
        String token = JwtUtils.createToken(claim, secret);

        // 存储在Redis中 用什么类型存储？ string
        // 存储值是对象 这样方便扩展
        redisService.setCacheObject(getTokenKey(key), loginUser, CacheConstants.EXP, TimeUnit.MINUTES);

        return token;
    }

    public void refreshLoginUser(String userKey, LoginUser loginUser) {
        refreshLoginUser(userKey, loginUser, CacheConstants.EXP, TimeUnit.MINUTES);
    }

    public void refreshLoginUser(String userKey, LoginUser loginUser, Long ttl, TimeUnit timeUnit) {
        String key = getTokenKey(userKey);
        LoginUser cacheLoginUser = redisService.getCacheObject(key, LoginUser.class);
        cacheLoginUser.setNickName(loginUser.getNickName());
        cacheLoginUser.setAvatar(loginUser.getAvatar());
        redisService.setCacheObject(key, cacheLoginUser, ttl, timeUnit);
    }

    // 获取 token的key
    private String getTokenKey(String key) {
        return CacheConstants.LOGIN_USER_KEY + key;
    }

    // 延迟Token时间
    public void extendToken(Claims claims) {
//        Claims claims = null;
//        try {
//            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
//            if (claims == null) { // 这里不适合直接抛异常或返回
//                log.error("token {} 解析失败", token);
//                return;
//            }
//        } catch (Exception e) {
//            log.error("token {} 解析失败 e {}", token, e.getMessage());
//        }
//
//        String userKey = JwtUtils.getUserKey(claims); //获取jwt中的key

        String userKey = getUserKey(claims);
        if (userKey == null)   {
            return;
        }
        String tokenKey = getTokenKey(userKey);
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire != null && expire <= CacheConstants.REFRESH_TIME) {
            // 还存在并且小于指定时间
            redisService.expire(tokenKey, CacheConstants.EXP, TimeUnit.MINUTES);
        }
    }

    // 通过token和secret获取用户的在Redis中的唯一标识
    public String getUserKey(Claims claims) {
        if (claims == null) return null;
        //获取jwt中的key
        return JwtUtils.getUserKey(claims);
    }

    private String getUserKey(String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        //获取jwt中的key
        return JwtUtils.getUserKey(claims);
    }

    public Long getUserId(Claims claims) {
        if (claims == null) return null;
        return Long.parseLong(JwtUtils.getUserId(claims));
    }

    public Claims getClaims(String token, String secret) {
        if (token == null) return null;
        Claims claims = null;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) { // 这里不适合直接抛异常或返回
                log.error("token {} 解析失败", token);
                return null;
            }
            return claims;
        } catch (Exception e) {
            log.error("token {} 解析失败 e {}", token, e.getMessage());
            return null;
        }
    }


    // 获取用户的登录信息
    public LoginUserVO getLoginUserVO(String token, String secret) {
        LoginUser loginUser = getLoginUser(token, secret);
        if (loginUser == null) {
            // 一般情况下是已经过期了
            throw new RuntimeException("登录用户信息获取失败");
        }
        LoginUserVO loginUserVO = loginUser.toVO();
        return loginUserVO;
    }

    public LoginUser getLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return null;
        }
        LoginUser loginUser  = redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);
        return loginUser;
    }


    public boolean delLoginUser(String token, String secret, UserIdentity identity) {
        LoginUser loginUser = getLoginUser(token, secret);
        if (loginUser == null || loginUser.getIdentity() != identity.getValue()) {
            // 用户不存在 或者 权限不匹配
            return false;
        }

        return redisService.deleteObject(getTokenKey(getUserKey(token, secret)));
    }
}
